package com.lagou.api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CreateSession implements Watcher {


    //CountDownLatch工具类使一个线程等待
    private static CountDownLatch countDownLatch = new CountDownLatch(1);


    /**
     * 创建会话
     *
     * @param args
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        /*
             客户端可以通过创建一个zk实例来连接zk服务器
             new Zookeeper(connectString,sesssionTimeOut,Wather)
             connectString: 连接地址:IP:端口
             sesssionTimeOut:会话超时时间:单位毫秒
             Wather:监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
         */

        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSession());
        System.out.println(zooKeeper.getState());
        //线程等待
        countDownLatch.await();
        System.out.println(zooKeeper.getState());
        System.out.println("客户端与服务端建立会话成功=========");
    }

    //当前类实现了Watcher接口，重写了process方法，该方法负责处理来自Zookeeper服务端的 watcher通知，
    // 在收到服务端发送过来的SyncConnected事件之后，解除主程序在CountDownLatch上 的等待阻塞，至此，会话创建完毕
    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("执行了process方法");
            countDownLatch.countDown();
        }
    }
}
